#!/usr/bin/env node

const fs = require('fs');
const path = require('path');

// Get command line arguments
const args = process.argv.slice(2);

if (args.length < 1) {
  console.log('Usage: node remove-demo.js <demo-name>');
  console.log('Example: node remove-demo.js MyNewDemo');
  process.exit(1);
}

const demoName = args[0]; // e.g., MyNewDemo

// Validate demo name (should be in PascalCase)
if (!/^[A-Z][a-zA-Z0-9]*$/.test(demoName)) {
  console.error('Demo name should be in PascalCase (e.g., MyNewDemo)');
  process.exit(1);
}

// File paths
const demosDir = path.join(__dirname, 'src', 'demos');
const demoFile = path.join(demosDir, `${demoName}.vue`);
const registryFile = path.join(__dirname, 'src', 'demoRegistry.js');
const loaderFile = path.join(__dirname, 'src', 'demoLoader.js');
const utilsFile = path.join(__dirname, 'src', 'utils', 'demoUtils.js');

// Check if demo exists
if (!fs.existsSync(demoFile)) {
  console.warn(`Demo file ${demoName}.vue does not exist! But we'll still remove references from registry files.`);
}

// Create kebab-case name for matching in registry files
const kebabCaseName = demoName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
const propertyName = kebabCaseName.includes('-') ? `'${kebabCaseName}'` : kebabCaseName;

// Update demo registry
if (fs.existsSync(registryFile)) {
  let registryContent = fs.readFileSync(registryFile, 'utf8');
  
  // Create regex to match the entire demo entry in registry
  const demoEntryRegex = new RegExp(`\\s*{\\s*id:\\s*'${kebabCaseName}'.*?category:.*?\\n\\s*},?\\s*\\n`, 's');
  registryContent = registryContent.replace(demoEntryRegex, '\n');
  
  fs.writeFileSync(registryFile, registryContent);
  console.log(`Updated demo registry: ${registryFile}`);
}

// Update demo loader
if (fs.existsSync(loaderFile)) {
  let loaderContent = fs.readFileSync(loaderFile, 'utf8');
  
  // Create regex to match the loader entry
  const loaderEntryRegex = new RegExp(`\\s*${propertyName}:\\s*\\(\\) => import\\('.*?'\\),?\\s*\\n`, 'g');
  loaderContent = loaderContent.replace(loaderEntryRegex, '\n');
  
  fs.writeFileSync(loaderFile, loaderContent);
  console.log(`Updated demo loader: ${loaderFile}`);
}

// Update demo utils
if (fs.existsSync(utilsFile)) {
  let utilsContent = fs.readFileSync(utilsFile, 'utf8');
  
  // Create regex to match the utils entry
  const utilsEntryRegex = new RegExp(`\\s*${propertyName}:\\s*'.*?',?\\s*\\n`, 'g');
  utilsContent = utilsContent.replace(utilsEntryRegex, '\n');
  
  fs.writeFileSync(utilsFile, utilsContent);
  console.log(`Updated demo utils: ${utilsFile}`);
}

// Delete demo file if it exists
if (fs.existsSync(demoFile)) {
  fs.unlinkSync(demoFile);
  console.log(`Deleted demo component: ${demoFile}`);
}

console.log('\nDemo removal completed!');